import random
import sys
import time

from libs.action import WebDriverAction
from libs.cache import Cache
from libs.game import Game
from libs.image import ImageTool
from libs.log import Log
from libs.movement import Movement
from libs.task_helper import TaskHelper
from libs.trade_helper import TradeHelper
from libs.window import AdsWindow

honey_lands = {
    "4025": {'up': 4.5},
    "4027": {'up': 4.5},
    "2780": {'left': 0.2, 'up': 4.5},
    "2781": {'up': 4},
    "2782": {'up': 3, 'right': 3.2},
    "2783": {'up': 3.5},
    "2784": {'up': 4},
    "2072": {'up': 4.5},
    "2074": {'up': 4.5},
    "1629": {'up': 4, 'left': 2.5, 'right': 5.1},
    "2655": {'up': 3},
    "2218": {'up': 3},
}

if __name__ == "__main__":
    parser = TaskHelper.default_args_parser('Honey')
    parser.add_argument('--init', type=int, default=0)
    args = parser.parse_args()
    task_helper = TaskHelper.from_args(args)

    user_id = args.user_id
    init = args.init
    log = Log(user_id)

    try:
        driver = AdsWindow(user_id).open(False)
        game = Game(driver, user_id)
        action = WebDriverAction(driver, user_id=user_id)
        movement = Movement(driver)
        image_tool = ImageTool(driver)
        cache = Cache()
        trade_helper = TradeHelper(driver, user_id)

        game.enter_game()
        game.collect_mail()
        game.snapshot(user_id, 'before honey')
        game.get_backpack()
        queen_bee_qty = game.get_backpack_qty('Queen Bee')

        queen_bee_cache_key = f'queen_bee_required_{user_id}'
        if init == 0:
            requirement_cache = cache.get(queen_bee_cache_key)
            cache.set(queen_bee_cache_key, 0, 0)
            if requirement_cache:
                init = int(requirement_cache)
        if init > queen_bee_qty:
            try:
                trade_helper.goto_buy_position()
                filter_input = trade_helper.open_market_buy()
                trade_helper.market_buy_item(filter_input, 'Queen Bee', init - queen_bee_qty)
                action.escape()
                action.escape()
                game.get_backpack()
            except:
                task_helper.add_task('honey.py', args={"init":init}, delay_seconds=0, ignore_running=True, priority=9, retry=True)
                task_helper.task_fail()
                sys.exit()

        queen_bee_total_required = 0
        if game.get_energy() < 150:
            task_helper.task_giveup()
            sys.exit()

        for _ in range(3):
            try:
                land_nos = list(honey_lands.keys())
                random.shuffle(land_nos)
                for land_no in land_nos:
                    if cache.get(f'honey_{user_id}_{land_no}'):
                        continue
                    queen_bee_required = 0
                    action.goto_land_from_portal(land_no)
                    steps = honey_lands.get(land_no)
                    for direction in steps:
                        move_seconds = steps.get(direction)
                        if direction == 'up':
                            movement.keep_move_up(move_seconds)
                        if direction == 'left':
                            movement.keep_move_left(move_seconds)
                        if direction == 'right':
                            movement.keep_move_right(move_seconds)
                        if direction == 'down':
                            movement.keep_move_down(move_seconds)
                        time.sleep(1)
                        bee_house_locs = image_tool.find_all_targets('bee_house.png')
                        log.info(f"land_no={land_no}, bee_house={len(bee_house_locs)}")
                        for x, y in bee_house_locs:
                            y += 32
                            bubble_text = action.hover_bubble(x, y)
                            if bubble_text:
                                if bubble_text.startswith('Sweet Honey') or bubble_text.startswith('Honey'):
                                    action.click()
                                if bubble_text == 'Queen Bee Required':
                                    queen_bee_index, _ = game.get_backpack_index_and_qty('Queen Bee')
                                    if queen_bee_index:
                                        game.use_backpack_item(queen_bee_index)
                                        time.sleep(0.1)
                                        action.click_by_offset(x, y, wait_secons=0.1)
                                        action.escape()
                                    else:
                                        queen_bee_required += 1
                            time.sleep(0.1)

                    cache.set(f'honey_{user_id}_{land_no}', 1, 45 * 60)
                    queen_bee_total_required += queen_bee_required

                if queen_bee_total_required > 0:
                    cache.set(queen_bee_cache_key, queen_bee_total_required, 24 * 60 * 60)
                    Log('notify').info(f'[{user_id}] ({queen_bee_total_required}) queen_bee required')

                if game.get_backpack_qty('Wax') > 50 or game.get_backpack_qty('Honey') > 300:
                    trade_helper.goto_sell_position()
                    trade_helper.open_shop_sell()
                    trade_helper.sell_item('Wax', 1111, price_delta=-1)
                    trade_helper.sell_item('Honey', 1111, price_delta=-1)
                    action.escape()
                else:
                    action.goto_spec()
                task_helper.task_success()
                break
            except:
                continue
        game.snapshot(user_id, 'after honey', include_skills=False)
    except Exception as e:
        task_helper.task_fail()
        task_helper.add_task('honey.py', delay_seconds=0, ignore_running=True, priority=9, retry=True)
        raise e

